package com.atguigu.gulimall.product.exception;

import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;

import static com.atguigu.common.exception.BizCodeEnum.UNKNOW_EXCEPTION;
import static com.atguigu.common.exception.BizCodeEnum.VAILD_EXCEPTION;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice("com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handVaildException(MethodArgumentNotValidException e) {
        log.info("数据校验出现问题:{}，异常类型:{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        //获取校验结果
        result.getFieldErrors().forEach((item) -> {
            //FieldError 获取错误提示
            String message = item.getDefaultMessage();
            //获取错误属性名字
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(VAILD_EXCEPTION.getCode(), VAILD_EXCEPTION.getMessage()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handException(Throwable e) {
        log.error("错误:",e);
        return R.error(UNKNOW_EXCEPTION.getCode(),UNKNOW_EXCEPTION.getMessage());
    }
}
